﻿// ------------------------------------------------------------------------------
//  © 2008 OpenUpon™.  All rights reserved.
// ------------------------------------------------------------------------------
using System;
using Castle.ActiveRecord;
using NHibernate.Expression;

namespace CastUpon.Entities {
	[ActiveRecord]
	public class Listener : ActiveRecordBase<Listener> {
		private Int64 hits;
		private int id;
		private string ipAddress;
		private PodcastChannel podcastChannel;

		[PrimaryKey]
		public int Id {
			get { return this.id; }
			set { this.id = value; }
		}

		[BelongsTo("PodcastChannelId")]
		public PodcastChannel PodcastChannel {
			get { return this.podcastChannel; }
			set { this.podcastChannel = value; }
		}

		[Property]
		public string IpAddress {
			get { return this.ipAddress; }
			set { this.ipAddress = value; }
		}

		[Property]
		public long Hits {
			get { return this.hits; }
			set { this.hits = value; }
		}

		public static int GetListenersCount() {
			return Count();
		}

		public static bool SimilarExist(Listener listener) {
			return Exists(Expression.Conjunction().Add(Expression.Eq("IpAddress", listener.IpAddress)).Add(Expression.Eq("PodcastChannel", listener.PodcastChannel)));
		}

		public static Listener GetFirstSimilarListener(Listener listener) {
			return FindFirst(Expression.Conjunction().Add(Expression.Eq("IpAddress", listener.IpAddress)).Add(Expression.Eq("PodcastChannel", listener.PodcastChannel)));
		}

		public static void TallyHit(Listener listener) {
			Listener listenerFound = GetFirstSimilarListener(listener) ?? listener;
			listenerFound.Hits++;
			listenerFound.Save();
		}
	}
}